package com.yzh.croom.config;

import com.yzh.croom.service.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.Set;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;
    @Autowired
    private UserDetailsServiceImpl userDetailsService;

       @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.headers().frameOptions().sameOrigin().httpStrictTransportSecurity().disable();
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/x-admin/**").permitAll()
                .antMatchers("/admin/**").hasAuthority("admin")
                .antMatchers("/student/**").hasAuthority("student")
                .antMatchers("/teacher/**").hasAuthority("teacher")
                .anyRequest().authenticated();
        http.formLogin()
                .loginPage("/userLogin").permitAll()
                .usernameParameter("account")
                .passwordParameter("password")
                .defaultSuccessUrl("/")//.successHandler(new LoginSuccessHandler())
                .failureUrl("/userLogin?error");
        http.logout()
                .logoutUrl("/mylogout")
                .logoutSuccessUrl("/userLogin");
        http.rememberMe()
                .rememberMeParameter("rememberme")
                .tokenValiditySeconds(200)
                .tokenRepository(tokenRepository());
    }

 /*  @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**","/fonts/**","/images/**","/js/**","/lib/**");
    }*/

    @Bean
    public JdbcTokenRepositoryImpl tokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        return jdbcTokenRepository;
    }

   /* private class LoginSuccessHandler implements AuthenticationSuccessHandler {
        @Override
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
            Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
            String path = request.getContextPath() ;
            String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
            if (roles.contains("admin")){
                response.sendRedirect(basePath+"admin/toAdmin");
                return;
            }else if (roles.contains("teacher")){
                response.sendRedirect(basePath+"teacher/toTeacher");
                return;
            }else if (roles.contains("student")) {
                response.sendRedirect(basePath + "student/toStudent");
                return;
            }else{
                response.sendRedirect(basePath+"userLogin");
            }
        }
    }*/
}
